package com.xiaotu.spider.mgtv.pageprocessor;

import com.xiaotu.common.exception.SpiderException;
import com.xiaotu.common.exception.SpiderExceptionCode;
import com.xiaotu.common.model.TVProcessDataModel;
import com.xiaotu.common.util.*;
import com.xiaotu.spider.APageProcessor;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;

import java.util.*;

/**
 * 芒果 电视剧，网剧，网大 播放量 (数据来源于骨朵:因为芒果平台数据加密)
 */
@Component("MGTVPlayCountPageProcessor")
public class MGTVPlayCountPageProcessor extends APageProcessor {

    private Map<String, String> headers = null;

    {
        headers = new HashMap<String, String>();
        headers.put("Accept", PropertiesUtil.getProperty("GuDuo.site.Accept"));
        headers.put("Accept-Encoding", PropertiesUtil.getProperty("GuDuo.site.Accept-Encoding"));
        headers.put("Accept-Language", PropertiesUtil.getProperty("GuDuo.site.Accept-Language"));
        headers.put("Cache-Control", PropertiesUtil.getProperty("GuDuo.site.Cache-Control"));
        headers.put("Connection", PropertiesUtil.getProperty("GuDuo.site.Connection"));
        headers.put("Cookie", PropertiesUtil.getProperty("GuDuo.site.Cookie"));
        headers.put("Host", PropertiesUtil.getProperty("GuDuo.site.Host"));
        headers.put("User-Agent", PropertiesUtil.getProperty("GuDuo.site.User-Agent"));
    }

    //搜索列表
    public static final String SIMPLE_DETAIL =
            "http://ev.guduodata.com/show/simpleDetail/%s";

    //累计播放量
    public static final String TOTAL_PLAYCOUNT =
            "http://ev.guduodata.com/playcount/simpleReview/%s";

    @Override
    protected Request getStartRequest(JSONObject target) {
        return new Request("http://ev.guduodata.com/show/like?name="
                + KeywordEncode.encode(target.getString("tvName")));
    }

    @Override
    public String getPageDataType(Page page) {
        String url = page.getUrl().toString();
        if (url.contains("/show/like?name="))
            return Constants.PageDataType.SEARCH_LIST;
        else if (url.contains("/playcount/simpleReview"))
            return Constants.PageDataType.TV_RECORD;
        else
            return null;
    }

    @Override
    public void process(Page page) {
        Map<String, Object> tvMap = page.getRequest().getExtras();
        switch (this.getPageDataType(page)) {
            case Constants.PageDataType.SEARCH_LIST:
                this.searchListProcess(page, tvMap);
                break;
            case Constants.PageDataType.TV_RECORD:
                this.tvRecordProcess(page, tvMap);
                break;
            default:
                break;
        }
    }

    private void searchListProcess(Page page, Map<String, Object> tvMap) {
        String rawText = page.getRawText();
        if (StringUtils.isEmpty(rawText))
            throw new SpiderException(
                    SpiderExceptionCode.DataInvalideException);
        JSONObject jsonObject = JSONObject.fromObject(rawText);
        JSONArray list = jsonObject.getJSONObject("data").getJSONArray("list");
        list.stream().forEach(j -> {
            String jsonp = HttpUtils.httpGetJSONP(String.format(SIMPLE_DETAIL, ((JSONObject) j).getString("id")), headers);
            if (StringUtils.isEmpty(jsonp))
                throw new SpiderException(
                        SpiderExceptionCode.DataInvalideException);
            JSONObject detailObject = JSONObject.fromObject(jsonp);
            String pageTvType = TVProcessUtils.getTVType(detailObject.getString("category"));
            JSONArray actor_info_list = detailObject.getJSONArray("actor_info");
            JSONArray platform_img_list = detailObject.getJSONArray("platform_img_list");
            List<String> platformList = new ArrayList<String>();
            platform_img_list.stream().forEach(img -> {
                if (img.toString().contains("mamgguo")) {
                    platformList.add("芒果TV");
                }
            });
            if (!platformList.contains("芒果TV"))
                throw new SpiderException(
                        SpiderExceptionCode.DataInvalideException);
            List<String> pageActors = new ArrayList<String>();
            actor_info_list.stream().limit(10).forEach(actor -> {
                JSONObject actorInfo = (JSONObject) actor;
                pageActors.add(actorInfo.getString("actorName"));
            });
            String pageTvName = detailObject.getString("show_name");
            List<String> pageDirectors = Arrays.asList(detailObject.getString("director").split("[/,，]"));
            if (TVProcessUtils.tvMatched(tvMap, pageTvName, pageTvType, pageActors, pageDirectors)) {
                PageUtils.addTargetRequest(page, String.format(TOTAL_PLAYCOUNT, ((JSONObject) j).getString("id")), tvMap);
            }
        });

    }


    private void tvRecordProcess(Page page, Map<String, Object> tvMap) {
        String res = page.getRawText();
        if (StringUtils.isEmpty(res))
            throw new SpiderException(
                    SpiderExceptionCode.DataInvalideException);
        JSONObject jsonObject = JSONObject.fromObject(res);
        String totalPlayCount = jsonObject.getString("total_play_count");
        totalPlayCount = totalPlayCount.replace(".0", "");
        if (StringUtils.isEmpty(totalPlayCount) || Integer.parseInt(totalPlayCount) <= 0)
            throw new SpiderException(
                    SpiderExceptionCode.DataInvalideException);
        page.putField(TVProcessDataModel.class.getName(), new TVProcessDataModel(tvMap.get("tvid").toString(),
                tvMap.get("tvName").toString(),
                Constants.SiteName.MGTV, totalPlayCount, null, null));
    }

    @Override
    protected String getSpiderType() {
        return Constants.SpiderTaskType.TV_GUDUO;
    }
}